import React from 'react';
import style from "./index.module.scss";
import md5 from "js-md5";
import submitBtn from "../../base/SubmitBtn/index";
import PassWord from "../../base/PassWord/index";
import {login} from '../../serverAPI/index';
import {isMobile,isPassWord} from "../../common/data/_regExpHandler";
import {user} from "../../common/data/_dataStructure";
import {connect} from "react-redux";
import {request} from '../../request/request'
class Login extends React.Component{
    constructor(props){
        super(props);
        this.state={
            actionMode: 1, // 1 密码登录； 2 验证码登录； 0 注册
            headTitle:"登录",
            showAlert:false,
            userInfo:{
                userHeadUrl: require("../../common/image/user-head-default.png").default,
                phonenum:"",
                password:"",
                nickname:"",
                signature:"认识你们,很开心~",
                stuAuth:true,
            },
            verfitycode:"",
            code:null
        };
        this.tempPhonenum = "";

        this.callAlert=this.callAlert.bind(this);
    }

    setActionMode(mode){
        let headTitles = ["注册","登录","登录"];
        this.setState({
            actionMode:mode,
            headTitle:headTitles[mode],
        })
    }

    callAlert(flag,msg){
        this.setState({showAlert:flag,msg})
    }

    getVerfityCode(){
       request({url:"/getVerfityCode"}).then(res=>{
            if(res.data.code==="01"){
                alert(res.data.data)
                this.setState({
                    code:res.data.data
                })
            }else{
                alert("请求错误")
            }
       })
    }

    register(){
        let {phonenum,password,nickname} = this.state.userInfo;
        let userInfo = {phonenum,password,nickname};
        if(!isMobile.test(phonenum)) return alert("手机号格式不正确");
        if(!isPassWord.test(password)) return alert("密码：以字母开头，长度在4 ~ 6位之间，只能包含字符、数字和下划线。");
        if(this.state.code!==this.state.verfitycode) return alert('验证码错误')
        userInfo = Object.assign({},user,userInfo);
        userInfo.password = md5(userInfo.password);
        // console.log(userInfo.password);
        // alert("调用注册接口")
        request({
            url:"/register",
            method:"POST",
            data:{
                phonenum:userInfo.phonenum,
                password:userInfo.password,
                nickname:userInfo.nickname
            }
        }).then(res=>{
                console.log(res);
                if(res.data.code==="01"){
                    alert("注册成功")
                    this.setActionMode(1)
                }else if(res.data.code==="04"){
                    alert("服务器错误")
                }else{
                    alert("手机号或昵称已被注册")
                }
                
        },err=>{
            console.log(err);
        })
    }

    login(){
        if(this.state.actionMode == 1){
            let {phonenum,password} = this.state.userInfo;
            if(!phonenum || !password) return this.callAlert(true,"“手机号”或“密码”不能为空！");
            let userInfo = {phonenum, password: md5(password)};
            request({
                url:"/login",
                method:"GET",
                params:{
                    phonenum:userInfo.phonenum,
                    password:userInfo.password,
                }
            }).then(res=>{
                if(res.data.code==="01"){
                    localStorage.setItem("userList",JSON.stringify(res.data.data))
                    this.props.updataUser(res.data.data)
                    localStorage.removeItem("userList_temp");
                    this.props.history.push('/home')
                }else{
                    alert("用户或密码错误")
                }
            })
        }else{
            if(this.phonenum.value==="") return this.callAlert(true,"“手机号”或“昵称”不能为空！");
            if(this.state.code!==this.state.verfitycode) return alert('验证码错误')
            request({
                url:"/logins",
                method:"GET",
                params:{
                    phonenum:this.phonenum.value,
                }
            }).then(res=>{
                if(res.data.code==="01"){
                    localStorage.setItem("userList",JSON.stringify(res.data.data))
                    this.props.updataUser(res.data.data)
                    this.props.history.push('/home')
                }else{
                    alert("用户或密码错误")
                }
            })
        }
    }

    componentDidMount(){
        setTimeout(()=>{
            this.loginRoot.style.marginLeft="0";
        },50);

        let temp = localStorage.getItem("ReactProjectLoginUserTemp");
        if(temp){
            let userInfo = JSON.parse(temp);
            console.log(userInfo)
            this.tempPhonenum = userInfo.phonenum;
            this.setState({userInfo});
        }
    }

    render(){

        let formBody = [
            // --- --- 注册 
            (<div className={style["login-form"]}>

                <input type="text" className={style["userpoor-input"]} placeholder="手机号"
                    value = {this.state.userInfo.phonenum}
                    onChange={(e)=>{
                        let {userInfo} = this.state;
                        userInfo.phonenum = e.target.value;
                        this.setState({userInfo});
                    }}
                 />

                <input type="text" className={style["userpoor-input"]} placeholder="昵称"
                    value = {this.state.userInfo.nickname}
                    onChange={(e)=>{
                        let {userInfo} = this.state;
                        userInfo.nickname = e.target.value;
                        this.setState({userInfo});
                    }}
                 />
                <p className={style["verifty-box"]}>
                    <input type="text" className={style["userpoor-inputs"]} placeholder="验证码"
                        value = {this.state.verfitycode}
                        onChange={(e)=>{
                            this.setState({verfitycode: e.target.value});
                        }}
                    />
                    <button className={style["userpoor-btn"]}
                        onClick={()=>{this.getVerfityCode()}}
                    >发送验证码</button>
                </p>

                <PassWord className={style["userpoor-input"]} 
                        placeholder="密码" select="1" reg={isPassWord} max="8" code=""
                        onChange={(e)=>{ 
                            let userInfo = {...this.state.userInfo};
                            userInfo.password = e.value;
                            this.setState({userInfo});
                    }}/>

                <p>{submitBtn({content:"同意协议并注册", click:()=>this.register()})}</p>
            </div>),
            // --- --- 密码登录 
            (<div className={style["login-form"]}>
                <input type="text" className={style["userpoor-input"]} placeholder="手机号/昵称"
                    value = {this.state.userInfo.phonenum}
                    onChange={(e)=>{
                        let {userInfo} = this.state;
                        userInfo.phonenum = e.target.value;
                        this.setState({userInfo});
                    }}
                 />

                <div>
                    <PassWord className={style["userpoor-input"]} 
                        placeholder="密码" select="1" reg={isPassWord} max="6" code=""
                        onChange={(e)=>{ 
                            let userInfo = {...this.state.userInfo};
                            userInfo.password = e.value;
                            this.setState({userInfo});
                    }}/>
                    <p><span style={{visibility:"hidden"}}>忘记密码</span> <span onClick={()=>{this.setActionMode(2)}}>验证码登录</span> </p>
                </div>
                <p>{submitBtn({content:"登 录", click:()=>this.login()})}</p>
            </div>),
            // --- --- 验证码登录 
            (<div className={style["login-form"]}>
                <input type="text" className={style["userpoor-input"]} placeholder="手机号/昵称" ref={c=>this.phonenum=c} />
                <div>
                    <p className={style["verifty-box"]}>
                        <input type="text" className={style["userpoor-inputs"]} placeholder="验证码"
                            value = {this.state.verfitycode}
                            onChange={(e)=>{
                                this.setState({verfitycode: e.target.value});
                            }}
                        />
                        <button className={style["userpoor-btn"]}
                            onClick={()=>{this.getVerfityCode()}}
                        >发送验证码</button>
                    </p>
                    <p><span style={{marginLeft:"auto"}} onClick={()=>{this.setActionMode(1)}}>密码登录</span> </p>
                </div>
                <p>{submitBtn({content:"登 录", click:()=>this.login()})}</p>
             </div>),
        ]

        return (
            <div className={`${style["login-root"]}`} ref = {loginRoot=>this.loginRoot=loginRoot} >
                <div className={style["login-head"]}>
                    <img className={style["user-head-img"]} src={this.state.userInfo.userHeadUrl} />
                </div>
                {formBody[this.state.actionMode]}

                {this.state.actionMode
                  ? <p className={style["foot-link"]}>
                        还没有账号？<b onClick={()=>{this.setActionMode(0)}}>去注册</b>
                    </p>
                  : <p className={style["foot-link"]}>
                        已注册账号？<b onClick={()=>{this.setActionMode(1)}}>去登录</b>
                    </p>
                }
                <span className={style.status}>{this.state.actionMode?"登录":"注册"}</span>
            </div>
        )
    }
}

const mapStateToProps = (state)=>{
    return {userInfo:state.userInfo};
}
const mapDispatchToProps= (dispatch)=>{
    return {
        updataUser:(user)=>{
            dispatch({type:"UPDATEUSER", data:user});
        },
        addUser:(user)=>{
            dispatch({type:"ADDUSER", data:user});
        }
    }
}

export default connect(mapStateToProps,mapDispatchToProps)(Login);